<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ImageAdminController
 *
 * @author dro
 */

namespace Gairal\AdminBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Gairal\CoreBundle\Form\ImageType;
use Gairal\CoreBundle\Entity\Image;

class ImageAdminController extends Controller {

    public function indexAction() {
        //Call addAction to save a new image il request is POST
        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
            $this->addAction($request);

        $listImages = $this->getDoctrine()
                ->getManager()
                ->getRepository('GairalCoreBundle:Image')
                ->findAll();

        return $this->render('GairalAdminBundle:Image:index.html.twig', array(
                    'action' => 'Admin - Images',
                    'listImages' => $listImages
        ));
    }

    public function addAction($request = null) {

        $image = new Image();
        $form = $this->createForm(new ImageType(), $image);
            
        if ($request == null) {
            return $this->render('GairalAdminBundle:Image:add.html.twig', array(
                        'form' => $form->createView()
            ));
        }
        if ($request->getMethod() == 'POST') {
            $form->bind($request);
            if ($form->isValid()) {

                $em = $this->getDoctrine()->getManager();
                $em->persist($image);
                $em->flush();

                $this->get('session')->getFlashBag()->add('info', 'Image "' . $image->getName() . '" added');
                return $this->redirect($this->generateUrl('AdminImage'));
            }else
                $this->get('session')->getFlashBag()->add('error', $form->getErrorsAsString());
        }
    }

    public function removeAction(Image $image) {
        
        if ($image != null) {
            $em = $this->getDoctrine()
                    ->getManager();
            $em->remove($image);
            $em->flush();
            
            $this->get('session')->getFlashBag()->add('info', 'Image "' . $image->getName() . '" removed');
        }
        else
            $this->get('session')->getFlashBag()->add('error', 'Image not removed, error in url');

        return $this->redirect($this->generateUrl('AdminImage'));
    }

}

?>
